<template>
  <el-dialog
    :title="$t('IMPORT')"
    :visible.sync="visible"
    width="450px"
    :before-close="close"
    append-to-body
    @open="open"
  >
    <div v-if="!success && !error">
      <div class="white-space-normal">
        1.{{ $t('BEFORE_IMPORTING_PLEASE') }}
        <a v-if="downloadTplData" class="exportClick" @click="downloadTemplate">
          {{ $t('EXPORT_TEMPLATE') }}
        </a>
        <a v-else class="exportClick" :href="downTemplateUrl">
          {{ $t('EXPORT_TEMPLATE') }}
        </a>,{{ $t('ENTER_IMPORT_IN_TEMPLATE') }}
      </div>
      <div class="text-color white-space-normal" v-html="$t(importTips)" />
    </div>
    <div v-if="success" class="text-success">{{ $t('NODE_IMPORT_SUCCESS') }}</div>
    <div v-if="error" class="text-danger">{{ $t('IMPORT_FAILD') }}</div>
    <div v-if="error" class="text-color" style="white-space: pre-wrap;" v-html="errorMsg" />
    <template slot="footer">
      <div class="flex align-center justify-end">
        <el-button class="mr-2" @click="close">{{ $t('CANCEL') }}</el-button>
        <el-upload
          ref="upload"
          :headers="headers"
          :limit="1"
          :action="actionUrl"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :on-error="uploadFail"
          :accept="'.xlsx'"
        >
          <el-button slot="trigger" class="ml-10" size="mini" type="primary">{{
            $t('IMPORT')
          }}</el-button>
        </el-upload>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import config from '@/config'
  import { downloadFile } from '@/utils/common'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  export default {
    name: 'ConfImportDialog',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      templateUrl: {
        type: String,
        default: ''
      },
      importUrl: {
        type: String,
        default: '',
        required: true
      },
      serviceName: {
        type: String,
        default: 'oen',
        required: true
      },
      importTips: {
        type: String,
        default: 'NODE_IMPORT_TIPS',
        required: true
      },
      downloadTplData: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        actionUrl: '',
        headers: {
          token: localStorage.getItem('token')
        },
        success: false,
        error: false,
        errorMsg: '',
        loading: null
      }
    },
    computed: {
      ...mapGetters([
        'getUserId',
        'getUser'
      ])
    },
    created() {
      const location = window.location
      this.downTemplateUrl = location.pathname + this.templateUrl
      this.actionUrl = config.baseUrl + config.services[this.serviceName] + this.importUrl
    },
    methods: {
      open() {
        this.success = false
        this.error = false
        this.errorMsg = ''
      },
      showImport() {
        this.importData = {
          success: false,
          error: false,
          errorMsg: ''
        }
        this.importVisible = true
      },
      beforeUpload(file) {
        const fileType = file.name.substr(-5)
        let canUpload = true
        if (fileType !== '.xlsx') {
          canUpload = false
          this.$message.error(this.$t('MUST_XLSX'))
        }
        if (canUpload) {
          this.loading = this.$loading({
            background: 'rgba(255, 255, 255, 0.1)'
          })
        }
        return canUpload
      },
      uploadSuccess(data) {
        console.log('uploadSuccess', data)
        this.loading.close()
        this.loading = null
        this.$refs.upload.clearFiles()
        if (!data.data) {
          this.success = false
          this.error = true
          this.errorMsg = data.message
          this.addLog(false)
        } else {
          this.success = true
          this.error = false
          this.errorMsg = ''
          this.$message.success(this.$t('IMPORT_SUCCESS'))
          this.close(true)
          this.addLog(true)
        }
      },
      uploadFail(e) {
        this.loading.close()
        this.loading = null
        this.$message.error(e)
        this.addLog(false)
      },
      // 下载模板
      downloadTemplate() {
        this.downloadTplData.func()
          .then(res => {
            downloadFile(res, this.downloadTplData.name)
          })
          .catch(() => {})
      },
      close(data) {
        this.$emit('close', data)
      },
      addLog(result = true) {
        let obj = {}
        if (this.importUrl === '/import/importNode') {
          obj = {
            api: this.importUrl,
            item: 'MENU_NODE_MANAGER', // 节点管理
            terminal: 'NODE_IMPORT', // 导入（新增）
            object: '/',
            operateResult: result,
            content: JSON.stringify({
              currentUserId: this.getUserId,
              i18nKey: 'IMPORT_NODE_LOG'
            })
          }
        }
        if (this.importUrl === '/region/impData') {
          obj = {
            api: this.importUrl,
            item: 'MENU_REGION_MANAGER', // 区域管理
            terminal: 'IMPORT_REGION', // 导入
            object: '/',
            operateResult: result,
            content: JSON.stringify({
              currentUserId: this.getUserId,
              i18nKey: 'IMPORT_REGION_MANAGER_LOG'
            })
          }
        }
        if (this.importUrl === '/import/importCable') {
          obj = {
            api: this.importUrl,
            item: 'MENU_CABLE_MANAGER', // 光缆管理
            terminal: 'NODE_IMPORT', // 导入
            object: '/',
            operateResult: result,
            realName: this.getUser.realName,
            content: JSON.stringify({
              currentUserId: this.getUserId,
              i18nKey: 'IMPORT_CABLE_MANAGER_LOG'
            })
          }
        }
        // 记录导入导出日志
        try {
          OperateLogApi.addLog(obj)
        } catch (error) {
          console.log(error)
        }
      }
    }
  }
</script>

<style lang="scss">
  @import '@/assets/css/mixin.module.scss';
  .exportClick {
    cursor: pointer;
    @include themeify {
      color: themed('textFontColor');
    }
  }
</style>
